// 资源加载器 - 控制并发加载和优先级
class ResourceLoader {
    constructor() {
        this.config = window.PERFORMANCE_CONFIG || {};
        this.loadingResources = new Map(); // 正在加载的资源
        this.loadedResources = new Set();  // 已加载的资源
        this.queue = [];                   // 等待加载的资源队列
        this.maxConcurrent = this.config.resource?.lazyLoad?.maxConcurrent || 3;
        this.currentConcurrent = 0;        // 当前并发加载数
    }

    // 动态加载JavaScript文件
    loadScript(url, options = {}) {
        // 如果已经加载，直接返回
        if (this.loadedResources.has(url)) {
            return Promise.resolve();
        }
        
        // 如果正在加载，返回现有的Promise
        if (this.loadingResources.has(url)) {
            return this.loadingResources.get(url);
        }
        
        const promise = new Promise((resolve, reject) => {
            // 检查是否为关键资源
            const isCritical = this.config.resource?.critical?.includes(url);
            
            // 如果是关键资源或未启用懒加载，立即加载
            if (isCritical || !this.config.resource?.lazyLoad?.enabled) {
                this._loadScriptNow(url, options, resolve, reject);
            } else {
                // 否则加入队列，按优先级加载
                this.queue.push({
                    url,
                    options,
                    resolve,
                    reject,
                    priority: options.priority || 0
                });
                this._processQueue();
            }
        });
        
        // 保存Promise
        this.loadingResources.set(url, promise);
        
        return promise;
    }

    // 立即加载脚本
    _loadScriptNow(url, options, resolve, reject) {
        if (this.currentConcurrent >= this.maxConcurrent) {
            // 如果达到最大并发数，加入队列等待
            this.queue.push({
                url,
                options,
                resolve,
                reject,
                priority: options.priority || 0
            });
            this._processQueue();
            return;
        }
        
        this.currentConcurrent++;
        
        const script = document.createElement('script');
        script.src = url;
        script.async = options.async !== false; // 默认异步
        script.defer = !!options.defer;
        
        script.onload = () => {
            this.currentConcurrent--;
            this.loadedResources.add(url);
            this.loadingResources.delete(url);
            resolve(url);
            this._processQueue(); // 处理队列中的下一个资源
        };
        
        script.onerror = (error) => {
            this.currentConcurrent--;
            this.loadingResources.delete(url);
            reject(new Error(`Failed to load script: ${url}`));
            this._processQueue(); // 处理队列中的下一个资源
        };
        
        document.head.appendChild(script);
    }

    // 预加载资源
    preload(url, asType = 'script') {
        if (this.loadedResources.has(url) || this.loadingResources.has(url)) {
            return;
        }
        
        const link = document.createElement('link');
        link.rel = 'preload';
        link.href = url;
        link.as = asType;
        
        // 对于脚本，添加crossorigin属性
        if (asType === 'script') {
            link.crossOrigin = 'anonymous';
        }
        
        link.onload = () => {
            console.log(`Preloaded: ${url}`);
        };
        
        link.onerror = () => {
            console.warn(`Failed to preload: ${url}`);
        };
        
        document.head.appendChild(link);
    }

    // 处理加载队列
    _processQueue() {
        // 按优先级排序（数字越大优先级越高）
        this.queue.sort((a, b) => b.priority - a.priority);
        
        while (this.currentConcurrent < this.maxConcurrent && this.queue.length > 0) {
            const item = this.queue.shift();
            this._loadScriptNow(item.url, item.options, item.resolve, item.reject);
        }
    }

    // 批量加载资源
    loadMultiple(urls, options = {}) {
        const promises = urls.map(url => this.loadScript(url, options));
        return Promise.all(promises);
    }
}

// 创建全局实例
window.resourceLoader = new ResourceLoader();

// 页面加载完成后预加载关键资源
document.addEventListener('DOMContentLoaded', function() {
    const config = window.PERFORMANCE_CONFIG || {};
    
    // 预加载关键资源
    if (config.resource?.critical) {
        config.resource.critical.forEach(url => {
            window.resourceLoader.preload(url, 'script');
        });
    }
    
    // 预加载普通资源
    if (config.resource?.preload) {
        config.resource.preload.forEach(url => {
            window.resourceLoader.preload(url, 'script');
        });
    }
});